package com.ktjy.examination.controller;

import com.ktjy.examination.entity.Users;
import com.ktjy.examination.entity.vo.R;
import com.ktjy.examination.service.BookService;
import com.ktjy.examination.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/api")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final long TOKEN_EXPIRE_TIME = 30 * 60; // token有效期半小时

    @PostMapping("/login")
    public R login(@RequestBody Users users) {
        // 验证用户名和密码长度
        if (users.getUserCode() == null || users.getUserCode().length() != 5) {
            return R.fail("用户名长度必须为5位");
        }
        if (users.getPassword() == null || users.getPassword().length() < 6) {
            return R.fail("密码长度不能小于6位");
        }

        int result = userService.login(users);
        if (result > 0) {
            String token = UUID.randomUUID().toString();
            String redisKey = "token:" + token;
            redisTemplate.opsForValue().set(redisKey, users.getUserCode(), TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("userCode", users.getUserCode());
            return R.ok(data);
        }
        return R.fail("账号或密码错误");
    }

    @PostMapping("/logout")
    public R logout(@RequestHeader(value = "Authorization", required = false) String token) {
        if (token == null || token.isEmpty()) {
            return R.fail("未登录状态");
        }
        
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
            String redisKey = "token:" + token;
            Boolean deleted = redisTemplate.delete(redisKey);
            if (Boolean.TRUE.equals(deleted)) {
                return R.ok("退出登录成功");
            }
        }
        return R.fail("退出登录失败");
    }
}
